package com.gaogzhen.controller;

import com.gaogzhen.geetest.GeetestLib;
import com.gaogzhen.geetest.GeetestLibResult;
import com.gaogzhen.utils.IpUtil;
import com.gaogzhen.utils.R;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @version 1.0
 * @description geetest控制器
 * @date 2022-06-25 11:03
 */
@RestController
@RequestMapping("/gt")
public class GeetestController {

    @Autowired
    private GeetestLib geetestLib;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/register")
    @ApiOperation(value = "获取极验的第一次数据包---")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid" ,value = "用户验证的一个凭证")
    })
    public R<String> register(String uuid) {
        String digestmod = "md5";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("digestmod", digestmod);
        paramMap.put("user_id", uuid);
        paramMap.put("client_type", "web");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        paramMap.put("ip_address", IpUtil.getIpAddr(servletRequestAttributes.getRequest()));

        GeetestLibResult result = geetestLib.register(digestmod, paramMap);
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY, result.getStatus(), 180, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_USER_KEY + ":" + uuid, uuid, 180, TimeUnit.SECONDS);
        // 注意，不要更改返回的结构和值类型
        return R.ok(result.getData());
    }
}
